package org.lazy.generate.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
/**
 * 
 * @description 数据库操作工具类
 * @author Anan
 * @time 2013-9-22 下午2:45:38
 */
public class DBManagerUtil {
	private DBManagerUtil(){};
	
	public static void main(String[] args) {
		String jdbcClassName = "com.mysql.jdbc.Driver";
		String jdbcUrl = "jdbc:mysql://localhost:3306/mms?useUnicode=true&amp;characterEncoding=UTF-8";
		String username = "root";
		String password = "root";
		try {
			Connection coon = getMySqlConn(jdbcClassName, jdbcUrl, username, password);
			System.out.println(coon);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取MySQL数据库连接
	 */
	public static Connection getMySqlConn(String jdbcClassName,String jdbcUrl,String username,String password) throws SQLException, ClassNotFoundException{
		Class.forName(jdbcClassName);
		return DriverManager.getConnection(jdbcUrl, username, password);
	}

	
	/**
	 * 查询数据库表字段
	 */
	public static ResultSetMetaData queryTable(String jdbcClassName,String jdbcUrl,String username,String password,String tableName) throws Exception{
		Connection conn = null;
		PreparedStatement pment = null;
		ResultSet rs = null;
		ResultSetMetaData metaData = null;
		try {
			conn = DBManagerUtil.getMySqlConn(jdbcClassName, jdbcUrl, username, password);
			pment = conn.prepareStatement("select * from " + tableName + " where 1 = 2;");
			rs = pment.executeQuery();
			metaData = rs.getMetaData();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
//		finally {
//			DBManagerUtil.close(conn, pment, rs);
//		}
		return metaData;
	}
	
	/**
	 * @description 释放资源
	 */
	public static void close(Connection conn, Statement stmt, ResultSet rs) {

		try {
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (stmt != null) {
				stmt.close();
				stmt = null;
			}
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
